from threading import Thread
import time
import schedule
from flask import Flask, jsonify, request
from flask_cors import CORS

from python_service.real_stock_service import get_stock_data, transform_data_for_kline, get_realtime_rank, \
    get_real_list, get_point_real_data

app = Flask(__name__)
# 启用跨域支持，允许所有来源访问
CORS(app)


@app.errorhandler(500)
def handle_500_error(e):
    return jsonify({"code": "0", "message": "系统错误"}), 500


# API接口：获取日线、周线、月线数据
@app.route('/get_kline_data/<stock_code>/<freq>', methods=['GET'])
def get_daily_data_route(stock_code, freq):
    # 此处假设存在对应的函数来获取数据并转换格式，示例中为get_stock_data和transform_data_for_kline
    data = get_stock_data(stock_code, freq)
    # print(data)
    response = {
        "code": 1,
        "message": "",
        "data": data
    }
    return jsonify(response)


# API接口：获取实时涨跌幅排名数据
@app.route('/get_realtime_rank', methods=['GET'])
def get_realtime_rank_route():
    # 此处假设存在对应的函数来获取数据，示例中为get_realtime_rank
    df = get_realtime_rank()
    data = df.to_dict(orient='records')  # 转换为字典形式
    response = {
        "code": 1,
        "message": "",
        "data": data
    }
    return jsonify(response)


@app.route('/get_realtime_data/<stock_code>', methods=['GET'])
def get_index_realtime_stock_data(stock_code: str):
    result = []
    stock_real_list = get_real_list(stock_code)
    for stock_data in stock_real_list:
        data_dict = {
            "id": stock_data.id,
            "ts_code": stock_data.ts_code,
            "datetime": stock_data.datetime.strftime('%Y-%m-%d %H:%M:%S') if stock_data.datetime else None,
            "open": stock_data.open,
            "pre_close": stock_data.pre_close,
            "price": stock_data.price,
            "high": stock_data.high,
            "low": stock_data.low,
            "increase": stock_data.increase,
            "ratio": stock_data.ratio,
            "volume": stock_data.volume,
            "amount": stock_data.amount
        }
        result.append(data_dict)
    response = {
        "code": 1,
        "message":"",
        "data":result
    }
    return jsonify(response)


@app.route("/get_point_stock_data",methods=['GET'])
# 获取股票实时数据,此接口只是用于获取一些不具有连续性的股票实时数据，主要用于展示
# 股票某一时间点的情况
def get_point_stock_data():
    json_data = request.get_json()
    print(json_data)
    data = get_point_real_data(json_data)
    response = {
        "code": 1,
        "message": "",
        "data": data
    }
    return jsonify(response)

def run_flask():
    app.run(debug=False, use_reloader=False)  # 禁用重新加载


def run_scheduler():
    while True:
        # print("检查调度列表")
        schedule.run_pending()  # 执行所有的待办任务
        time.sleep(60)


if __name__ == '__main__':
    # app.run(debug=False)
    flask_thread = Thread(target=run_flask)
    scheduler_thread = Thread(target=run_scheduler)

    flask_thread.start()  # 启动 Flask 服务
    scheduler_thread.start()  # 启动定时任务调度
